package com.association.main.controller;



import com.association.main.common.R;
import com.association.main.domain.Clubs;
import com.association.main.domain.Users;
import com.association.main.service.ClubsService;
import com.association.main.service.UsersService;
import com.association.main.utils.JwtUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private UsersService usersService;

    @Autowired
    private ClubsService clubsService;


    /*
    *
    * 首页分页查询
    * */
    @GetMapping
    public R<Page> userList(int page, int pageSize, Users users,String sort){
        Page pageInfo = usersService.userList(page,pageSize,users,sort);
        return R.success(20000,pageInfo);
    }


    /*
    *
    * 社团选择社长页查询
    * */
    @GetMapping("/list")
    public R<List<Users>>  UsersOption(){
        LambdaQueryWrapper<Users> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Users::getRole,"member");
        List<Users> list = usersService.list(lambdaQueryWrapper);
        return R.success(list);
    }

    @PostMapping
    public R<String> add(@RequestBody Users users){
        users.setCreatedAt(LocalDateTime.now());
        users.setUpdatedAt(LocalDateTime.now());
        usersService.save(users);
        return R.success(20000,"添加成功");
    }

    @DeleteMapping
    public R<String> delete(@RequestBody Users users){
        if(users.getId()==1){
            return R.error("Admin用户不可删除！");
        }
        usersService.removeById(users.getId());
        return R.success(20000,"删除成功");
    }

    @PutMapping
    public R<String> update(@RequestBody Users users){
        usersService.updateById(users);
        return R.success(20000,"更新成功");
    }

    @PostMapping("/login")
    public R<Map> login(@RequestBody Users users){
        //1.查询用户名是否存在
        LambdaQueryWrapper<Users> usersLambdaQueryWrapper=new LambdaQueryWrapper<>();
        usersLambdaQueryWrapper.eq(Users::getUsername,users.getUsername());
        usersLambdaQueryWrapper.eq(Users::getPassword,users.getPassword());
        usersLambdaQueryWrapper.eq(Users::getRole,users.getRole());
        Users user = usersService.getOne(usersLambdaQueryWrapper);
        if(user != null){
            //如果用户存在，如果是社团管理员，则查找是否分配有社团进行管理
            if(user.getRole().equals("member")){
                LambdaQueryWrapper<Clubs> clubsLambdaQueryWrapper=new LambdaQueryWrapper<>();
                clubsLambdaQueryWrapper.eq(Clubs::getCreatedBy,user.getId());
                List<Clubs> list = clubsService.list(clubsLambdaQueryWrapper);
                if(list.size()<=0){
                    return R.error("当前社团管理员没有分配社团管理权限！无法登录!");
                }
            }
           //生成token对象
            String jwtToken = JwtUtil.getJwtToken(user);
            Map map=new HashMap();
            map.put("userid",user.getId());
            map.put("username",users.getUsername());
            map.put("roles",users.getRole());
            map.put("token",jwtToken);
            return R.success(map);
        }
        return R.error("账号或密码错误");

    }

    //通过token获取用户角色
    @RequestMapping("/roleCheck")
    public R<Map> loginrole(String token){
        //通过接受到的token获取角色
        String userType = JwtUtil.getUserType(token);
        Integer userId = JwtUtil.getUserId(token);
        Users users = usersService.getById(userId);
        Map map=new HashMap();
        String[] role=new String[1];
        role[0]=userType;
        map.put("roles",role);
        map.put("email",users.getEmail());
        map.put("phone",users.getPhone());
        map.put("name",users.getName());
        map.put("username",users.getUsername());
        LambdaQueryWrapper<Clubs> clubsLambdaQueryWrapper=new LambdaQueryWrapper<>();
        clubsLambdaQueryWrapper.eq(Clubs::getCreatedBy,userId);
        List<Clubs> list = clubsService.list(clubsLambdaQueryWrapper);
        map.put("clubs",list);
        return R.success(map);
    }

    //
    //退出
    //
    @PostMapping("/logout")
    public R<Map> logout(){
        Map map=new HashMap();
        String token=null;
        map.put("token",token);
        return R.success(map);
    }


    @PutMapping("/editor")
    public R<String> editor(@RequestBody Users users, HttpServletRequest request){
        String token = request.getHeader("token");
        Integer userId = JwtUtil.getUserId(token);
        LambdaUpdateWrapper<Users> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(Users::getId,userId);
        boolean update = usersService.update(users, lambdaUpdateWrapper);
        return update==true?R.success("修改个人资料成功"):R.error("修改失败，可能未做更改");
    }






}
